<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="84px">
      <el-form-item >
        <el-select @change="changeKeyType"  v-model="queryParamsSearch.key" placeholder="" style="width: 120px;" >
          <el-option v-for="item in keyList" :value="item.value" :label="item.label" :key="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label=""  style="margin-left: -34px;" >
        <el-input style="width:200px;border-radius: 0;" v-if="queryParamsSearch.key !== 'deviceStatus'"
                  :disabled="!singleSearch"
                  v-model="queryParamsSearch.keyWord"
                  placeholder="请输入内容"
                  clearable
                  @keyup.enter="handleQuery"
        />
        <el-select v-else style="width: 200px;border-radius: 0;" v-model="queryParamsSearch.keyWord"
                   :disabled="!singleSearch">
          <el-option label="在线" :value="1"></el-option>
          <el-option label="离线" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="changeSearchType" plain :type="singleSearch?'':'primary'">高级</el-button>
      </el-form-item>
      <div v-show="!singleSearch">
        <el-form-item label="设备序列号" prop="serialNumber">
          <el-input style="width:200px;"
                    v-model="queryParams.serialNumber"
                    placeholder="请输入设备编号"
                    clearable
                    @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="设备编号" prop="deviceNumber">
          <el-input style="width:200px;"
                    v-model="queryParams.deviceNumber"
                    placeholder="请输入设备编号"
                    clearable
                    @keyup.enter="handleQuery"
          />
        </el-form-item>


        <el-form-item label="辖区" prop="areaName">
          <el-input style="width:200px;"
                    v-model="queryParams.areaName"
                    placeholder="请输入辖区"
                    clearable
                    @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="街道" prop="streetName">
          <el-input style="width:200px;"
                    v-model="queryParams.streetName"
                    placeholder="请输入街道"
                    clearable
                    @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="社区" prop="community">
          <el-input style="width:200px;"
                    v-model="queryParams.community"
                    placeholder="请输入社区"
                    clearable
                    @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="小区" prop="residentialName">
          <el-input style="width:200px;"
                    v-model="queryParams.residentialName"
                    placeholder="请输入小区"
                    clearable
                    @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="投放点名称" prop="deviceName">
          <el-input style="width:200px;"
                    v-model="queryParams.deviceName"
                    placeholder="请输入地址"
                    clearable
                    @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="设备品牌" prop="deviceBrand">
          <el-input style="width:200px;"
                    v-model="queryParams.deviceBrand"
                    placeholder="请输入设备品牌"
                    clearable
                    @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="设备型号" prop="deviceModel">
          <el-input style="width:200px;"
                    v-model="queryParams.deviceModel"
                    placeholder="请输入设备型号"
                    clearable
                    @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="设备状态" prop="deviceStatus">
          <el-select v-model="queryParams.deviceStatus" placeholder="请选择设备状态" clearable
                     style="width: 200px">
            <el-option
                v-for="dict in wvp_device_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </div>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['wvp:surveillance:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['wvp:surveillance:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['wvp:surveillance:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport"
                   v-hasPermi="['wvp:surveillance:import']">导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain @click="handleSyncDeviceStatus"
                   v-hasPermi="['wvp:surveillance:syncDeviceStatus']">强制刷新
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['wvp:surveillance:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="tableRef" :height="tableHeight" v-loading="loading" :data="surveillanceList"
              @selection-change="handleSelectionChange">
      <el-table-column min-width="48px" fixed="left" show-overflow-tooltip type="selection" width="55" align="center"/>
      <el-table-column min-width="48px" label="序号" fixed="left" show-overflow-tooltip type="index" width="55"
                       align="center"/>
      <!--      <el-table-column min-width="100px"  show-overflow-tooltip   label="主键" align="center" prop="id" />-->
      <!--            <el-table-column min-width="100px"  fixed="left"  show-overflow-tooltip   label="设备名称" align="center" prop="deviceName"/>-->
      <el-table-column min-width="180px" fixed="left" show-overflow-tooltip label="设备序列号" align="center"
                       prop="serialNumber"/>
      <el-table-column min-width="180px" fixed="left" show-overflow-tooltip label="设备编号" align="center"
                       prop="deviceNumber"/>
      <el-table-column min-width="80px" fixed="left" show-overflow-tooltip label="设备状态" align="center"
                       prop="deviceStatus">
        <template #default="scope">
          <dict-tag :options="wvp_device_status" :value="scope.row.deviceStatus"/>
        </template>
      </el-table-column>
      <!--      <el-table-column min-width="100px"  show-overflow-tooltip   label="省份名称" align="center" prop="proviceName" />-->
      <!--      <el-table-column min-width="100px"  show-overflow-tooltip   label="市名称" align="center" prop="cityName" />-->
      <el-table-column min-width="160px" show-overflow-tooltip label="区域" align="center" prop="areaName"/>
      <el-table-column min-width="200px" show-overflow-tooltip label="街道" align="center" prop="streetName"/>
      <el-table-column min-width="200px" show-overflow-tooltip label="社区" align="center" prop="community"/>
      <el-table-column min-width="180px" show-overflow-tooltip label="小区" align="center" prop="residentialName"/>
      <el-table-column min-width="220px" show-overflow-tooltip label="投放点名称" align="center" prop="deviceName"/>
      <!--      <el-table-column min-width="100px"  show-overflow-tooltip   label="ip地址" align="center" prop="ip" />-->
      <!--      <el-table-column min-width="100px"  show-overflow-tooltip   label="物理地址" align="center" prop="macAddress" />-->
      <el-table-column min-width="100px" show-overflow-tooltip label="设备品牌" align="center" prop="deviceBrand"/>
      <el-table-column min-width="140px" show-overflow-tooltip label="设备型号"  align="center" prop="deviceModel"/>

      <el-table-column min-width="100px" show-overflow-tooltip label="备注信息" align="center" prop="remark"/>
      <el-table-column min-width="180px" show-overflow-tooltip label="经度" align="center" prop="longitude"/>
      <el-table-column min-width="180px" show-overflow-tooltip label="纬度" align="center" prop="latitude"/>
      <el-table-column min-width="100px" show-overflow-tooltip fixed="right" label="操作" align="center"
                       class-name="small-padding fixed-width" width="200px;">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['wvp:surveillance:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['wvp:surveillance:remove']">删除
          </el-button>
          <el-button link type="primary" @click="handleDetail(scope.row)"
                     v-hasPermi="['wvp:surveillance:detail']">详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <plugin-form ref="pluginFormRef" @close="close"></plugin-form>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                 :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport"/>
              是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                     @click="importTemplate">下载模板
            </el-link>
          </div>
        </template>
      </el-upload>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Surveillance">
import PluginForm from './components/Form.vue'
import {useRouter} from "vue-router"
import {listSurveillance, getSurveillance, delSurveillance, syncDeviceStatus} from "@/api/wvp/surveillance";
import {getToken} from "@/utils/auth";

const pluginFormRef = ref()
const {proxy} = getCurrentInstance();
const {wvp_device_status} = proxy.useDict('wvp_device_status');

const surveillanceList = ref([]);
const router = useRouter()

const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryParamsSearch = ref({
  key: "serialNumber",
  keyWord: ""
})
const keyList = reactive([
  {label: "设备序列号", value: "serialNumber"},
  // {label: "设备编号", value: "deviceNumber"},
  // {label: "投放点", value: "deviceName"},
  // {label:"地址",value:"address"},
  // {label: "社区", value: "community"},
  // {label: "小区", value: "residentialName"},
  {label: "设备品牌", value: "deviceBrand"},
  {label: "设备型号", value: "deviceModel"},
  // {label: "设备状态", value: "deviceStatus"},

])

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceName: "",
    serialNumber: "",
    deviceNumber: "",
    proviceName: "",
    proviceCode: "",
    cityName: "",
    cityCode: "",
    areaName: "",
    areaCode: "",
    address: "",
    community: "",
    residentialName: "",
    ip: "",
    macAddress: "",
    deviceBrand: "",
    deviceModel: "",
    deviceStatus: "",
    deleted: "",
  },
});


const {queryParams, rules} = toRefs(data);
const singleSearch = ref(true)

function resetMyForm(){
  queryParams.value={
    pageNum: 1,
    pageSize: 10,
    deviceName: "",
    serialNumber: "",
    deviceNumber: "",
    proviceName: "",
    proviceCode: "",
    cityName: "",
    cityCode: "",
    areaName: "",
    areaCode: "",
    address: "",
    community: "",
    residentialName: "",
    ip: "",
    macAddress: "",
    deviceBrand: "",
    deviceModel: "",
    deviceStatus: "",
    deleted: "",
  }
}
/** 查询AI摄像头列表 */
function getList() {
  loading.value = true;

  if(singleSearch.value) {
    proxy.resetForm("queryRef");
    queryParams.value[queryParamsSearch.value.key]=queryParamsSearch.value.keyWord;
  }
  listSurveillance(queryParams.value).then(response => {
    surveillanceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function changeKeyType(){
  queryParamsSearch.value.keyWord=''
  resetMyForm();
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  if(singleSearch.value){
    queryParamsSearch.value.key='serialNumber';
    queryParamsSearch.value.keyWord=''
  }
  resetMyForm()
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


/** 新增按钮操作 */
function handleAdd() {

  pluginFormRef.value.begin(false);
}


/** 修改按钮操作 */
function handleUpdate(row) {
  const _id = row.id || ids.value
  pluginFormRef.value.begin(_id)
}

// 关闭刷新页面
function close(reset = false) {
  if (reset) {
    resetQuery()
  } else {
    getList()
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除AI摄像头编号为"' + _ids.length + '"条数据项？').then(function () {
    return delSurveillance(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

function handleSyncDeviceStatus() {

  syncDeviceStatus().then(response => {
    proxy.$modal.msgSuccess("刷新成功");
  })
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('wvp/surveillance/export', {
    ...queryParams.value
  }, `surveillance_${new Date().getTime()}.xlsx`)
}

getList();

function handleDetail(row) {
  router.push({
    path: "/surveillanceDetail",
    query: {
      id: row.id
    }
  })
}


const screenHeight = ref(window.innerHeight);
const tableHeight = ref(10);
const tableRef = ref();

function handleResize() {
  screenHeight.value = window.innerHeight;
  tableHeight.value = screenHeight.value - tableRef.value.$el.getBoundingClientRect().top - 80;
}

onMounted(() => {
  handleResize()
  window.addEventListener('resize', handleResize);
});
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
});


const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: {Authorization: "Bearer " + getToken()},
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/wvp/surveillance/importData"
});

/** 导入按钮操作 */
function handleImport() {
  upload.title = "AI摄像头导入";
  upload.open = true;
};

/** 下载模板操作 */
function importTemplate() {
  proxy.download("wvp/surveillance/importTemplate", {}, `AI摄像头_${new Date().getTime()}.xlsx`);
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};


function changeSearchType(){
  proxy.resetForm("queryRef");
  resetMyForm();
  queryParamsSearch.value.keyWord='';
  singleSearch.value=!singleSearch.value;
  nextTick(()=>{
    handleResize()
  })
}
</script>
<style scoped>
>>> .pagination-container .el-pagination {
  right: 40px !important;

}

>>> .pagination-container {
  margin-top: 0 !important;
}
</style>
